package com.study.java.utils;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.URL;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

/**
* @Name: DOM4JUtils
* @Description: XML-DOM4J解析工具包
* @Author: XXX
* @CreateDate: XXX
* @Version: V1.0
 */
public class DOM4JUtils {
	
	private static String XMLPATH = "users.xml" ;
	
	static {
		ClassLoader loader = DOM4JUtils.class.getClassLoader() ;
		URL url = loader.getResource(XMLPATH) ;
		XMLPATH = url.getPath() ;
	}
	
	/**
	* @Name: getDocument
	* @Description: 获取xml-Document对象
	* @Author: XXX
	* @Version: V1.0
	* @CreateDate: XXX
	* @Return: Document
	 */
	public static Document getDocument() {
		Document document = null ;
		try {
			SAXReader reader = new SAXReader() ;
			document = reader.read(XMLPATH) ;
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		return document ;
	}
	
	/**
	* @Name: writeXML
	* @Description: 将内存中的xml数据写入到xml文件中
	* @Author: XXX
	* @Version: V1.0
	* @CreateDate: XXX
	* @Parameters: @param document
	* @Return: void
	 */
	public static void writeXML(Document document) {
		OutputStream out = null ;
		OutputFormat format = null ;
		XMLWriter writer = null ;
		try {
			out = new FileOutputStream(XMLPATH) ;
			format = OutputFormat.createPrettyPrint() ;
			format.setEncoding("UTF-8") ;
			writer = new XMLWriter(out, format) ;
			writer.write(document) ;
		} catch (Exception e) {
			throw new RuntimeException(e) ;
		} finally {
			if(writer != null) {
				try {
					writer.close() ;
				} catch (Exception e) {
					e.printStackTrace() ;
				} finally {
					writer = null ;
				}
			}
			if(out != null) {
				try {
					out.close() ;
				} catch (Exception e) {
					e.printStackTrace() ;
				} finally {
					out = null ;
				}
			}
		}
	}
	

}

















